//
//  UserAgentUtil.m
//  YinYin
//
//  Created by chenliang on 15/11/16.
//  Copyright © 2015年 China Industrial Bank. All rights reserved.
//

#import "UserAgentUtil.h"
#import <UIKit/UIKit.h>
#import "UIDevice+IdentifierAddition.h"

@implementation UserAgentUtil{
    UIWebView *_tempWebview;
}

+(UserAgentUtil *)sharedInstance{
    static UserAgentUtil *instance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

//-(void)validateUserAgent{
//    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
//    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
//    NSUInteger index = [userAgent rangeOfString:@"/pdsm-uuid/"].location;
//    if (index == NSNotFound) {
//        NSString *pdsmuuid = [[NSUserDefaults standardUserDefaults]objectForKey:@"registrationID"];
//        if (pdsmuuid) {
//            userAgent = [NSString stringWithFormat:@"%@/pdsm-uuid/%@",userAgent,pdsmuuid];
//            NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:userAgent, @"UserAgent",nil];
//            [[NSUserDefaults standardUserDefaults]registerDefaults:dictionary];
//            [[NSUserDefaults standardUserDefaults]synchronize];
//        }
//    }
//}

-(void)setUserAgentUUID{
    NSString *pdsmuuid = [[UIDevice currentDevice]uniqueDeviceIdentifier];
    
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    UIWebView *tempWebview = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgent = [tempWebview stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    //截取前面
    NSUInteger index = [userAgent rangeOfString:@"/pdsm-uuid/"].location;
    if (index != NSNotFound) {
        userAgent = [userAgent substringToIndex:index];
    }
    userAgent = [NSString stringWithFormat:@"%@/pdsm-uuid/%@",userAgent,pdsmuuid];
    NSLog(@"userAgent = %@",userAgent);
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:userAgent, @"UserAgent",nil];
    [[NSUserDefaults standardUserDefaults]registerDefaults:dictionary];
    [[NSUserDefaults standardUserDefaults]synchronize];
}
@end
